package com.ruoyi.web.controller.user;

import com.ruoyi.system.domain.User;
import com.ruoyi.system.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/user")

public class UserLogin {
    //    controller层调service层
    //自动装配User

    @Autowired
    private UserService userService;
    public void setUserService(UserService userService){
        this.userService=userService;
    }
    @PostMapping("/login")
    @ResponseBody
    public Map<String,String> isLogin(@RequestBody Map<String,String> info,HttpSession session){
        System.out.println(info);
        HashMap<String, String> Error = new HashMap<>();
        Error.put("info","请输入正确的用户名和密码！");
        //传入的角色是员工
        if (info.get("role").equals("user")) {
            User user = userService.queryUserById(info.get("id"));
            if (user!=null){
                if (user.getPassword().equals(info.get("pwd"))) {
                    if (session.getAttribute("id") != null) {
                        session.removeAttribute("id");
                    }
                    System.out.println(user);
                    session.setAttribute("id", user);
                    session.setMaxInactiveInterval(3600);//设置会话最大维持时间1小时
                    HashMap<String, String> toFrame = new HashMap<>();
                    System.out.println("Loading on UserMain.jsp");
                    toFrame.put("redirect", "/user");
                    return toFrame;
                }
            }
        }
        return Error;
    }
    //员工登录成功
    @RequestMapping("/usermain")
    public String UserLogin(Model model,HttpSession session){
        Object user = session.getAttribute("id");
        model.addAttribute("user",user);
        return "usermain";
    }
}

